import 'dart:math';

import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/scan_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/basic_information/equip_instrument_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/get_my_unit_list_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

class RunTaskController extends GetxController {
  /// 单元列表
  List<GetMyUnitListEntity> unitList = [];

  // 进入巡检详情
  void goInspectionDetails(String? id) {
    if (id == null) {
      AppToast.showError('当前数据异常!');
      return;
    }
    Get.toNamed(AppRoutes.runTaskDetail, arguments: {'id': id, 'type': 0});
  }

  Future<void> scan(int index) async {
    final Map<String, dynamic> deviceMap = await ScanUtil.scanUnitQRReturnMap();
    if (deviceMap.isEmpty) {
      return;
    }
    // 墨水瓶扫码接口判断是否为当前单元
    final res = await HttpUtil().generateGetRequest<List<EquipInstrumentEntity>>(
      Interface.inkBottleScanning,
      queryParameters: {
        'deviceNo': deviceMap['ID'],
        'checkCode': deviceMap['time'],
        'unitId': unitList[index].tbBaseRiskUnitId,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        final double randomNumber = Random().nextDouble();
        // 设置百分之五十的几率进入人脸识别页面
        if (randomNumber < 0.5) {
          Get.toNamed(AppRoutes.faceAuth)?.then((value) {
            /// 从此页面返回，会返回一个 bool?
            /// - true：成功
            /// - false：失败
            /// - null：未识别
            if (value == true) {
              goInspectionDetails(unitList[index].tbBaseRiskUnitId);
            } else if (value == false) {
              AppToast.showWarning('人脸识别失败');
            } else {
              AppToast.showWarning('未识别');
            }
          });
        } else {
          goInspectionDetails(unitList[index].tbBaseRiskUnitId);
        }
      } else {
        AppToast.showWarning('请扫描本单元二维码');
      }
    });
    // Get.to(() {
    //   return CustomQrScanPage(
    //     onScanResult: (value) {
    //       final String str = _decrypt(value);
    //       AppToast.showSuccess('id:$str');
    //       goInspectionDetails(unitList[index].tbBaseRiskUnitId);
    //     },
    //   );
    // });
  }

  // 获取我的任务单元列表数据
  void getMyTaskUnitList() async {
    final response = await HttpUtil().generateGetRequest<List<GetMyUnitListEntity>>(Interface.myTaskUnitList).execute();
    response.onSuccess((result) {
      if (result.data != null) {
        unitList = result.data!;
        update();
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    getMyTaskUnitList();
    // getTaskCountdownData();
  }
}
